package com.szx.usercenter.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szx.usercenter.contance.ConstanceUser;
import com.szx.usercenter.domain.SysRole;
import com.szx.usercenter.domain.SysUser;
import com.szx.usercenter.mapper.SysUserMapper;
import com.szx.usercenter.service.SysUserRoleService;
import com.szx.usercenter.service.SysUserService;
import com.szx.usercenter.service.UserFileNumberService;
import com.szx.usercenter.util.JwtHelper;
import com.szx.usercenter.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yikonsh
 * @description 针对表【sys_user(用户信息表)】的数据库操作Service实现
 * @createDate 2024-05-11 09:54:35
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {

  @Autowired SysUserRoleService sysUserRoleService;
  @Autowired UserFileNumberService fileNumberService;

  @Override
  public SysUser getSefUser(SysUser user) {
    SysUser sysUser = ObjUtil.clone(user);
    sysUser.setPassword(null);
    return sysUser;
  }

  /**
   * 登录
   *
   * @param sysUser
   * @return
   */
  @Override
  public Response login(SysUser sysUser, HttpServletRequest request) {
    // 1.获取用户填写的用户名和密码
    String userName = sysUser.getUserName();
    String password = sysUser.getPassword();

    // 2.校验用户名密码
    if (userName == null || password == null) {
      return Response.error("用户名或密码不能为空");
    }
    SysUser one = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, userName));
    if (one == null) {
      return Response.error("用户名不存在");
    }

    if (!BCrypt.checkpw(password, one.getPassword())) {
      return Response.error("密码错误");
    }

    // 生成token
    String token = JwtHelper.createToken(one.getUserId(), one.getUserName());
    one.setToken(token);

    // 往Session中保存数据
    request.getSession().setAttribute(ConstanceUser.USER_LOGIN_STATE, one);

    // 获取角色信息
    List<SysRole> userRoleList = sysUserRoleService.getUserRoleList(one.getUserId());
    one.setSysRoleList(userRoleList);

    // 返回脱敏数据
    SysUser sefUser = this.getSefUser(one);

    return Response.rspData(sefUser);
  }

  /**
   * 注册
   *
   * @param username
   * @param password
   * @return
   */
  @Override
  public Response register(String username, String password) {
    // 1.用户名不能有特殊字符，并且必须超过6位数
    if (!username.matches("^[a-zA-Z0-9_-]{6,16}$")) {
      return Response.error("用户名必须超过6位数,并且不能有特殊字符");
    }
    // 2.密码必须超过6位数
    if (password.length() < 6) {
      return Response.error("密码必须超过6位数");
    }
    // 3.用户名不能重复
    if (this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, username)) != null) {
      return Response.error("用户名已存在");
    }
    // 4.添加用户到表中
    SysUser sysUser = new SysUser();
    sysUser.setUserName(username);
    sysUser.setNickName(username);
    sysUser.setPassword(BCrypt.hashpw(password, BCrypt.gensalt())); // 密码加密保存
    boolean isOk = this.save(sysUser);

    if (isOk) {
      // 给新用户添加一个默认的权限
      sysUserRoleService.setUserDefaultRole(sysUser);
      return Response.success();
    }
    return Response.error("注册失败");
  }

  /** 获取用户信息 */
  @Override
  public SysUser currentUser(HttpServletRequest request) {
    String token = JwtHelper.getToken(request);
    Long userId = JwtHelper.getUserId(token);
    SysUser user = this.getById(userId);
    List<SysRole> userRoleList = sysUserRoleService.getUserRoleList(userId);
    user.setSysRoleList(userRoleList);
    return getSefUser(user);
  }

  /** 更新用户密码 */
  @Override
  public Response updatePassword(String userName, String newPassword) {
    SysUser one = this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, userName));
    if (ObjectUtil.isEmpty(one)) {
      return Response.error("用户不存在");
    }
    one.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt()));
    this.updateById(one);
    return Response.success();
  }

  /** 分页查询用户 */
  @Override
  public Response getPageUserList(SysUser sysUser) {
    Page<SysUser> sysUserPage = new Page<>(sysUser.getCurrent(), sysUser.getPageSize());

    LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
    // 用户名称查询
    if (StrUtil.isNotEmpty(sysUser.getUserName())) {
      qw.like(SysUser::getUserName, sysUser.getUserName());
    }

    // 手机号查询
    if (StrUtil.isNotEmpty(sysUser.getPhonenumber())) {
      qw.like(SysUser::getPhonenumber, sysUser.getPhonenumber());
    }

    // 邮箱查询
    if (StrUtil.isNotEmpty(sysUser.getEmail())) {
      qw.like(SysUser::getEmail, sysUser.getEmail());
    }

    // 创建日期查询，查询当天内的所有数据
    if (ObjectUtil.isNotEmpty(sysUser.getCreateTime())) {
      // 将前端传来的日期转换为当天的开始时间
      Date startDate = DateUtil.beginOfDay(sysUser.getCreateTime());

      // 将结束日期设置为当天的结束时间
      Date endDate = DateUtil.endOfDay(startDate);

      qw.between(SysUser::getCreateTime, startDate, endDate);
    }

    this.page(sysUserPage, qw);

    // 返回的用户信息脱敏
    List<SysUser> userList = sysUserPage.getRecords();
    sysUserPage.setRecords(
        userList.stream()
            .map(
                user -> {
                  user.setSysRoleList(sysUserRoleService.getUserRoleList(user.getUserId()));
                  return getSefUser(user);
                })
            .collect(Collectors.toList()));

    return Response.rspData(sysUserPage);
  }

  /**
   * 添加新用户
   *
   * @param sysUser
   * @return
   */
  @Override
  public Response addUser(SysUser sysUser) {
    if (StrUtil.isNotEmpty(sysUser.getUserName())) {
      SysUser one =
          this.getOne(
              new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserName, sysUser.getUserName()));
      if (ObjectUtil.isNotEmpty(one)) {
        return Response.error("用户名已存在");
      }
    }
    if (StrUtil.isNotEmpty(sysUser.getEmail())) {
      SysUser one =
          this.getOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, sysUser.getEmail()));
      if (ObjectUtil.isNotEmpty(one)) {
        return Response.error("邮箱已存在");
      }
    }
    if (StrUtil.isNotEmpty(sysUser.getPhonenumber())) {
      SysUser one =
          this.getOne(
              new LambdaQueryWrapper<SysUser>()
                  .eq(SysUser::getPhonenumber, sysUser.getPhonenumber()));
      if (ObjectUtil.isNotEmpty(one)) {
        return Response.error("手机号已存在");
      }
    }
    if (StrUtil.isNotEmpty(sysUser.getPassword())) {
      sysUser.setPassword(BCrypt.hashpw(sysUser.getPassword(), BCrypt.gensalt()));
    } else {
      // 默认密码
      sysUser.setPassword(BCrypt.hashpw("123456", BCrypt.gensalt()));
    }
    if (this.save(sysUser)) {
      // 给新用户添加一个默认的权限
      sysUserRoleService.setUserDefaultRole(sysUser);
      // 分配初始容量
      fileNumberService.initUserFileNumber(sysUser.getUserId());
      return Response.success();
    }
    return Response.error();
  }
}
